<template>
  <div>

    <Category :scene="scene" />
    <el-card style="margin:10px 0">
      <div v-show="scene == 0">
        <el-button type="primary" size="default" @click="addAttr" icon="Plus">添加平台属性</el-button>
        <el-table border style="margin: 10px 0;" :data="attrArr">
          <el-table-column label="序号" type="index" align="center" width="80px">
          </el-table-column>
          <el-table-column label="属性名称" align="center" width="120px" prop="attrName">
          </el-table-column>
          <el-table-column label="属性值名称" align="center">
            <template #="{ row, $index }">
              <div>
                <el-tag style="margin: 5px;" v-for="(item, index) in row.attrValueList" :key="item.id">{{ item.valueName
                }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120px">
            <template #="{ row, $index }">
              <el-button type="primary" size="small" @click="updateAttr(row)" icon="Edit"></el-button>
              <el-popconfirm class="box-item" :title="`你确定删除已有${row.attrName}吗`" placement="bottom" @confirm="deleteAttr(row.id)">
                <template #reference> <el-button icon="Delete" size="small" type="primary"></el-button></template>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true" :model="attrParams">
          <el-form-item label="属性名称" prop="attrName">
            <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" size="default" icon="Plus" @click="addAttrValue">添加属性值</el-button>
        <el-button type="primary" size="default" @click="cancle">取消</el-button>
        <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
          <el-table-column width="80px" type="index" align="center" label="序号"></el-table-column>
          <el-table-column align="center" label="属性值名称">
            <template #="{ row, $index }">
              <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)"
                placeholder="请输入属性名称" size="small" v-model="row.valueName"></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作值操作">
                                  <template #="{ row, index }">
                            <el-button type="primary" size="small" icon="Delete"
                                @click="attrParams.attrValueList.splice(index, 1)"></el-button>
                        </template>
          </el-table-column>

        </el-table>

        <el-button type="primary" size="default" @click="save"
          :disabled="attrParams.attrValueList.length <= 0">保存</el-button>
        <el-button type="primary" size="default" @click="cancle">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeMount, reactive, ref, watch } from 'vue'
import { reqAddOrUpdateAttr, reqAttr, reqRemoveAttr } from '@/api/product/attr';
import useCategoryStore from '@/store/modules/category';
import { Attr, AttrValue } from '@/api/product/attr/type';
import { ElMessage } from 'element-plus';
let categoryStore = useCategoryStore();

let attrArr = ref<Attr[]>([])

let scene = ref<number>(0);
let attrParams = reactive<Attr>({
  attrName: "",//新增的属性的名字
  attrValueList: [//新增的属性值数组
  ],
  categoryId: '',//三级分类的ID
  categoryLevel: 3,//代表的是三级分类
})
//准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([]);

watch(() => categoryStore.c3Id, () => {
  attrArr.value = [];
  if (!categoryStore.c3Id) return;
  getAttr();
})
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  let result = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrArr.value = result.data
  }

}

const addAttr = () => {
  Object.assign(attrParams, {
    attrName: "",//新增的属性的名字
    attrValueList: [//新增的属性值数组
    ],
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,//代表的是三级分类
  })
  scene.value = 1;
}

const updateAttr = (row: Attr) => {
  scene.value = 1;
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))

}

const deleteAttr = async (attrId: number) => {
  let result = await reqRemoveAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功"
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败"
    });

  }
}

const cancle = () => {
  scene.value = 0
}
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true
  })
  nextTick(() => {
    inputArr.value[inputArr.value.length - 1].focus();
  })
}
const save = async () => {
  let result = await reqAddOrUpdateAttr(attrParams);
  if (result.code == 200) {
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功"
    })
    await getAttr()
  } else {

    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败"
    })
  }
}

//属性值表单元素失却焦点事件回调
const toLook = (row: AttrValue, $index: number) => {

  //非法情况判断1
  if (row.valueName.trim() == '') {
    //删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1);
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return;
  }
  //非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    //切记把当前失却焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });

  if (repeat) {
    //将重复的属性值从数组当中干掉
    attrParams.attrValueList.splice($index, 1);
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    })
    return;
  }
  //相应的属性值对象flag:变为false,展示div
  row.flag = false;
}

//属性值div点击事件
const toEdit = (row: AttrValue, $index: number) => {
  //相应的属性值对象flag:变为true,展示input
  row.flag = true;
  // nextTick:响应式数据发生变化,获取更新的DOM(组件实例)
  nextTick(() => {
    inputArr.value[$index].focus();
  })

}
onBeforeMount(()=>{
  categoryStore.$reset();
})
</script>

<style scoped lang="scss"></style>
